"""
绘图演示脚本
- 演示如何调用 utils/plot_style.py 的字体与风格设置函数
"""

import matplotlib.pyplot as plt
from utils.plot_style import setup_chinese_font, set_plot_style
import os
import yaml
from PIL import Image

# 读取 config.yaml 参数
with open("config.yaml", "r", encoding="utf-8") as f:
    config = yaml.safe_load(f)

# 工具函数

def ensure_dir(path):
    if not os.path.exists(path):
        os.makedirs(path)

def save_figure(fig, filename):
    fig_dir = config.get("figures_dir") or config.get("figure_path") or "figures"
    ensure_dir(fig_dir)
    path = os.path.join(fig_dir, filename)
    fig.savefig(path, dpi=300, bbox_inches='tight')
    print(f"图片已保存：{path}")
    return path

def show_all_images(image_paths):
    for path in image_paths:
        try:
            img = Image.open(path)
            img.show()
        except Exception as e:
            print(f"图片 {path} 打开失败：{e}")

if __name__ == "__main__":
    # 设置中文字体和绘图风格
    setup_chinese_font()
    style_cfg = {
        'style': 'darkgrid',
        'dpi': 300,
        'figsize': [8, 6],
        'bbox_inches': 'tight'
    }
    set_plot_style(style_cfg)

    # 强制全局中文字体为 Heiti TC，防止中文乱码
    plt.rcParams['font.sans-serif'] = ['Heiti TC']
    plt.rcParams['axes.unicode_minus'] = False

    # 示例数据
    x = [1, 2, 3, 4]
    y = [10, 20, 15, 25]

    plt.figure()
    plt.plot(x, y, marker='o')
    fontdict_title = {'family': 'Heiti TC', 'fontsize': 16}
    fontdict_label = {'family': 'Heiti TC', 'fontsize': 14}
    plt.title("中文标题示例", fontdict=fontdict_title)
    plt.xlabel("横轴：变量X", fontdict=fontdict_label)
    plt.ylabel("纵轴：变量Y", fontdict=fontdict_label)
    plt.grid(True)
    plt.tight_layout()
    img_path = save_figure(plt, "plot_demo.png")
    plt.show()
    show_all_images([img_path])
